﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using System.Data.Services.Client;
using iTraffic_ClientWP.iTrafficService;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework.Media;
using System.IO.IsolatedStorage;
using System.IO;
using Microsoft.Phone;
using System.Collections.Specialized;
using System.Net;
using System.IO;
using System.Device.Location;
using System.Text;
using System.Xml.Linq;
using Microsoft.Phone.Controls.Maps;
using Microsoft.Phone.Controls.Maps.Core;
using iTraffic_ClientWP.Model;
namespace iTraffic_ClientWP
{
 
    public partial class Upload : PhoneApplicationPage
    {
        CameraCaptureTask cameraCaptureTask;
        private GeoCoordinateWatcher _watcher;
        public HotPoints_Photos currentPhoto;
      

        private byte[] _imageBytes;
        private string flag;
        string filename;
        string _filename;
        int _id;
        int userID;
        short? _like;
        short? _dislike;
        string Latitude;
        string Longitude;

        double? _latitude;
        double? _longitude;

        int levelId;
        int hotPointId;

        static string serviceUriString = UrlConfig.SERVICE_URI_STRING;

        // Declare the service root URI.
        private Uri svcRootUri =
            new Uri(serviceUriString, UriKind.Absolute);

        // Declare our private binding collection.
        private DataServiceCollection<HotPoints_Photos> _myphotos;
        private DataServiceCollection<HotPoints> _hotpoints;
        private DataServiceCollection<HotPoints_Levels> _level;

        private iTrafficEntities _context;
        private bool cameraCancelled = false;

        public Upload()
        {
            InitializeComponent();
            cameraCaptureTask = new CameraCaptureTask();
            cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed);
            _watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
            _watcher.MovementThreshold = 10; // 10 meters
            _watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(OnStatusChanged);
            _watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(OnPositionChanged);
            _watcher.Start();
            
        }


        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (cameraCancelled == false)
            {
                cameraCaptureTask.Show();
            }
            else
            {
                return;
            }

            //cameraCaptureTask.Show();
        }
        /*----------------------------------------Location Service-------------------------------------------*/

        void OnStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            if (e.Status == GeoPositionStatus.Disabled)
                MessageBox.Show("The location service is currently turned off.");
            else if (e.Status == GeoPositionStatus.NoData)
                MessageBox.Show("No location data is currently available. Try again later.");
        }

        void OnPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            var epl = e.Position.Location;
            Latitude = epl.Latitude.ToString("0.000");
            Longitude = epl.Longitude.ToString("0.000");

        }

        private void cameraCaptureTask_Completed(object sender, PhotoResult e)
        {
            // Get back the last PhotoInfo in the collection, which we just added.
            //  currentPhoto = App.ViewModel.Photos[App.ViewModel.Photos.Count - 1];

            if (e.TaskResult == TaskResult.OK)
            {
                getHotPointList();
                getHotPointLevelList();
                //StartLocationService(GeoPositionAccuracy.High);
                // MessageBox.Show(Latitude);
                BitmapImage bitmap;

                DateTime currentTime = DateTime.Now;
                string day = currentTime.Day.ToString();
                string month = currentTime.Month.ToString();
                string year = currentTime.Year.ToString();
                string hour = currentTime.Hour.ToString();
                string minute = currentTime.Minute.ToString();
                string second = currentTime.Second.ToString();

                filename = day + month + year + hour + minute + second;

                _imageBytes = new byte[(int)e.ChosenPhoto.Length];
                e.ChosenPhoto.Read(_imageBytes, 0, _imageBytes.Length);
                e.ChosenPhoto.Seek(0, System.IO.SeekOrigin.Begin);

            
                cameraCancelled = true;
                bitmap = new BitmapImage();
                bitmap.SetSource(e.ChosenPhoto);

                e.ChosenPhoto.Position = 0;

                // Put Photo to Canvas
               // cnvUpload.Visibility = Visibility.Visible;
                this.PhotoImage.Source = bitmap;

                // 

                // MessageBox.Show("Upload Successfully !");
                saveToIsolatedStorage(e.ChosenPhoto, this.filename, "Images");

                //   watcher.Stop();
            }
            else
            {
                // Assume that the camera operation was cancelled,
                cameraCancelled = true;
            }
            // this.LoadTopRated();
            //  this.LoadMyPhoto();
        }

        private void saveToIsolatedStorage(Stream imageStream, string fileName, string imageFolder)
        {
            var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
            if (!isoFile.DirectoryExists(imageFolder))
            {
                isoFile.CreateDirectory(imageFolder);
            }
            if (isoFile.FileExists(this.filename))
            {
                isoFile.DeleteFile(this.filename);
            }

            string filePath = Path.Combine(imageFolder, fileName);
            using (var stream = isoFile.CreateFile(filePath))
            {
                BitmapImage bitmap = new BitmapImage();
                bitmap.SetSource(imageStream);

                WriteableBitmap wb = new WriteableBitmap(bitmap);
                wb.SaveJpeg(stream, wb.PixelWidth, wb.PixelHeight, 0, 85);
                // stream.Close();
            }

            using (var _imageStream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))
            {

                MediaLibrary library = new MediaLibrary();
                library.SavePicture(this.filename, _imageStream);
            }
        }
        /*---------------------------------------Upload-------------------------------------------*/
        public void upload()
        {

            int indexPoint = hotPoint_ListPicket.SelectedIndex;
            int indexLevel = hotPointLevel_ListPicket.SelectedIndex;

            HotPoints objPoint = _hotpoints[indexPoint];
            HotPoints_Levels objLevel = _level[indexLevel];

            levelId = objLevel.Id;
            hotPointId = objPoint.Id;


            string upload_url = UrlConfig.UPLOAD_PHOTO;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(upload_url);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
            
            goBack();
        }

        private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            try
            {

                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
                string encoding = "iso-8859-1";
                Stream postStream = request.EndGetRequestStream(asynchronousResult);
                string boundary = Guid.NewGuid().ToString();
                request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);

                string header = string.Format("--{0}", boundary);
                string footer = string.Format("--{0}--", boundary);

                StringBuilder contents = new StringBuilder();
                contents.AppendLine(header);

                string fileHeader = String.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"; ", "media", filename + ".jpg");
                string fileData = Encoding.GetEncoding(encoding).GetString(_imageBytes, 0, _imageBytes.Length);

                contents.AppendLine(fileHeader);
                contents.AppendLine(String.Format("Content-Type: {0};", "image/jpeg"));
                contents.AppendLine();
                contents.AppendLine(fileData);

                contents.AppendLine(header);
                contents.AppendLine(String.Format("Content-Disposition: form-data; name=\"{0}\"", "latitude"));
                contents.AppendLine();
                contents.AppendLine(Latitude);

                contents.AppendLine(header);
                contents.AppendLine(String.Format("Content-Disposition: form-data;  name=\"{0}\"", "longitude"));
                contents.AppendLine();
                contents.AppendLine(Longitude);

                contents.AppendLine(header);
                contents.AppendLine(String.Format("Content-Disposition: form-data;  name=\"{0}\"", "userid"));
                contents.AppendLine();
                //   contents.AppendLine(userID.ToString());
                contents.AppendLine("1");

                contents.AppendLine(header);
                contents.AppendLine(String.Format("Content-Disposition: form-data;  name=\"{0}\"", "levelId"));
                contents.AppendLine();
                contents.AppendLine(levelId.ToString());

                contents.AppendLine(header);
                contents.AppendLine(String.Format("Content-Disposition: form-data;  name=\"{0}\"", "hotPointId"));
                contents.AppendLine();
                contents.AppendLine(hotPointId.ToString());

                contents.AppendLine(footer);

                // Convert the string into a byte array. 
                byte[] byteArray = Encoding.GetEncoding(encoding).GetBytes(contents.ToString());

                // Write to the request stream. 
                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();

                // Start the asynchronous operation to get the response 
                request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
                //MessageBox.Show("Upload thanh cong !");
                //cnvUpload.Visibility = Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Co Loi !");
            }
        }
        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            try
            {

                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
                // End the operation 
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
                Stream streamResponse = response.GetResponseStream();
                StreamReader streamRead = new StreamReader(streamResponse);
                string responseString = streamRead.ReadToEnd();

                // Close the stream object 
                streamResponse.Close();
                streamRead.Close();

                // Release the HttpWebResponse 
                response.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show("Co Loi !");
            }
        }


        /*---------------------------------------- Get Hot Point List and Hot Point Level-----------------------*/
        private void getHotPointList()
        {

            // Load data from the data service.
            _context = new iTrafficEntities(svcRootUri);

            // Call Add Header to Request
            // _context.SendingRequest += new EventHandler<SendingRequestEventArgs>(OnSendingRequest);

            _hotpoints = new DataServiceCollection<HotPoints>(_context);

            // Load the data from the Photo feed.
            _hotpoints.LoadAsync(new Uri(UrlConfig.GET_HOT_POINT_LIST, UriKind.Absolute));

            // Register for the LoadCompleted event to turn off the progress bar and load Thumbnail.
            _hotpoints.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(GetHotPointList_LoadCompleted);
        }

        private void getHotPointLevelList()
        {

            // Load data from the data service.
            _context = new iTrafficEntities(svcRootUri);

            // Call Add Header to Request
            // _context.SendingRequest += new EventHandler<SendingRequestEventArgs>(OnSendingRequest);

            _level = new DataServiceCollection<HotPoints_Levels>(_context);

            // Load the data from the Photo feed.
            _level.LoadAsync(new Uri(UrlConfig.GET_HOT_POINT_LEVEL_LIST, UriKind.Absolute));

            // Register for the LoadCompleted event to turn off the progress bar and load Thumbnail.
            _level.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(GetHotPointLevelList_LoadCompleted);
        }

        private void GetHotPointList_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                // Make sure that we load all pages of the Photo feed.
                if (_hotpoints.Continuation != null)
                {
                    // Request the next page from the data service.
                    _hotpoints.LoadNextPartialSetAsync();
                }
                else
                {

                    List<HotPoint> _pointList = new List<HotPoint>();
                    for (int i = 0; i < _hotpoints.Count; i++)
                    {
                        HotPoints info = _hotpoints[i];
                        _pointList.Add(new HotPoint(info.Id, info.Name, info.Longitude, info.Latitude));
                    }

                    //hotPoint_ListPicket.ItemsSource
                    hotPoint_ListPicket.ItemsSource = _pointList;

                    //  InitializePushpins();

                }

            }
            else
            {
                if (MessageBox.Show(e.Error.Message, "Retry request?",
                    MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {

                }
            }
        }

        private void GetHotPointLevelList_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                // Make sure that we load all pages of the Photo feed.
                if (_level.Continuation != null)
                {
                    // Request the next page from the data service.
                    _level.LoadNextPartialSetAsync();
                }
                else
                {

                    List<Level> _levelList = new List<Level>();
                    for (int i = 0; i < _level.Count; i++)
                    {
                        HotPoints_Levels info = _level[i];

                        _levelList.Add(new Level(info.Id, info.Name));
                    }

                    hotPointLevel_ListPicket.ItemsSource = _levelList;

                }
                //  this.requestProgress.Visibility = Visibility.Collapsed;
                //  this.requestProgress.IsIndeterminate = false;
            }
            else
            {
                if (MessageBox.Show(e.Error.Message, "Retry request?",
                    MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {

                }
            }
        }

        private void btnUpload_Click(object sender, RoutedEventArgs e)
        {
            upload();
        }
        public void goBack()
        {
            //this.requestProgress.Visibility = Visibility.Collapsed;
            //this.requestProgress.IsIndeterminate = false;
            NavigationService.GoBack();
        }

    }
}